package com.shhc.crawler;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import net.coobird.thumbnailator.Thumbnails;

/**
 * 负责下载图片的任务，可以由线程执行 （Runnable）
 * 
 * 
 *
 */
public class DownloadTask implements Runnable {

	String url;
	String path;

	public DownloadTask(String url, String path) {
		super();
		this.url = url;
		this.path = path;
	}
	// 根据图片网络地址下载图片
	@Override
	public void run() {
		System.out.println(Thread.currentThread().getName());
		File file = null;
		File dirFile = null;
		FileOutputStream fos = null;

		HttpURLConnection httpCon = null;
		URLConnection con = null;
		URL urlObj = null;
		InputStream in = null;
		byte[] size = new byte[1024];
		int num = 0;
		try {
			String downloadName = url.substring(url.lastIndexOf("/") + 1);
			dirFile = new File(path);
			if (!dirFile.exists() && path.length() > 0) {
				if (dirFile.mkdir()) {
					System.out.println("creat document file \"" + path.substring(0, path.length() - 1) + "\" success...\n");
				}
			} else {
				file = new File(path + downloadName);
				fos = new FileOutputStream(file);
				if (url.startsWith("http")) {
					urlObj = new URL(url);
					con = urlObj.openConnection();
					httpCon = (HttpURLConnection) con;
					in = httpCon.getInputStream();
					while ((num = in.read(size)) != -1) {
						for (int i = 0; i < num; i++){
							fos.write(size[i]);
						}
							

					}
					System.out.println("             下载成功"+url+path);
					// 修改图片大小
					/* Thumbnails.of(file).size(1280,
					 1024).toFile(file);*/
				}
			}
		} catch (FileNotFoundException notFoundE) {
			System.out.println("找不到该网络图片....");
		} catch (NullPointerException nullPointerE) {
			System.out.println("找不到该网络图片....");
		} catch (IOException ioE) {
			System.out.println("产生IO异常.....");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				// 不论是否发生异常都会执行的
				if (fos != null) {
					fos.close();
				}

				if (con != null) {
					httpCon.disconnect();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}
}
